package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityBloodPigeonPairingBinding
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.ext.view.isEmpty
import me.hgj.jetpackmvvm.util.startActivity
import me.hgj.jetpackmvvm.util.startActivityForResult
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author      : hxw
 * @Date        : 2024/9/3 9:55
 * @Describe    : 配对
 */
class ActivityBloodPigeonPairing : BaseActivity<BreedingPigeonViewModel, ActivityBloodPigeonPairingBinding>() {

    private var maleId = 0
    private var femaleId = 0
    private var mSexType = ""
    private var mMaleUrl = ""
    private var mFemaleUrl = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 获取屏幕高度
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenHeight = displayMetrics.heightPixels
        // 监听软键盘状态
        mDatabind.llRootLayout.viewTreeObserver.addOnGlobalLayoutListener {
            val r = Rect()
            mDatabind.llRootLayout.getWindowVisibleDisplayFrame(r)
            /** 计算高度差 */
            val heightDiff = mDatabind.llRootLayout.height - (r.bottom - r.top)
            if (heightDiff > screenHeight / 4) {
                // 软键盘弹出，界面上移
                mDatabind.llRootLayout.scrollTo(0, heightDiff + 80)
            } else {
                // 软键盘收起，界面下移
                mDatabind.llRootLayout.scrollTo(0, 0)
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = getString(R.string.hint_pair)

        val type = intent.getStringExtra("type")//blood-种鸽进入,rear-作育管理进入
        if (type == "blood") {
            mSexType = intent.getStringExtra("sex").toString()
            if (mSexType == "雌") {
                mDatabind.llChooseFemalePigeon.isEnabled = false
            } else {
                mDatabind.llChooseFamePigeon.isEnabled = false
            }
            val mPigeonId = intent.getIntExtra("pigeonId", 0)
            onRefreshDetailInfo(mPigeonId)
        }
        refreshLayoutStatus()
    }

    private fun onRefreshDetailInfo(mPigeonId: Int) {
        showLoading(getString(R.string.loading))
        mViewModel.getBreedingPigeonInfo(mPigeonId.toString())
    }

    private fun refreshLayoutStatus() {
        if (mDatabind.tvMaleRingId.text.toString().trim().isEmpty()) {
            mDatabind.tvEditPairMale.isEnabled = false
            mDatabind.tvEditPairMale.setTextColor(ContextCompat.getColor(this, R.color.comm_text_gray_light))
            mDatabind.tvEditPairMale.setBackgroundResource(R.drawable.round_btn_gray25_b_g_light)
        } else {
            mDatabind.tvEditPairMale.isEnabled = true
            mDatabind.tvEditPairMale.setTextColor(ContextCompat.getColor(this, R.color.black))
            mDatabind.tvEditPairMale.setBackgroundResource(R.drawable.border_btn_male_pigeon_bg)
        }

        if (mDatabind.tvFemaleRingId.text.toString().trim().isEmpty()) {
            mDatabind.tvEditPairFemale.isEnabled = false
            mDatabind.tvEditPairFemale.setTextColor(ContextCompat.getColor(this, R.color.comm_text_gray_light))
            mDatabind.tvEditPairFemale.setBackgroundResource(R.drawable.round_btn_gray25_b_g_light)
        } else {
            mDatabind.tvEditPairFemale.isEnabled = true
            mDatabind.tvEditPairFemale.setTextColor(ContextCompat.getColor(this, R.color.black))
            mDatabind.tvEditPairFemale.setBackgroundResource(R.drawable.border_btn_female_pigeon_bg)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.btnStartPair,
            mDatabind.llChooseFamePigeon,
            mDatabind.llChooseFemalePigeon,
            mDatabind.tvEditPairMale,
            mDatabind.tvEditPairFemale,
            mDatabind.ivFemalePairPic,
            mDatabind.ivMalePairPic
        ) { it ->
            when (it) {
                mDatabind.ivMalePairPic -> {
                    if (mMaleUrl.isNotEmpty())
                        openBigImage(mDatabind.ivMalePairPic, mMaleUrl)
                }

                mDatabind.ivFemalePairPic -> {
                    if (mFemaleUrl.isNotEmpty())
                        openBigImage(mDatabind.ivFemalePairPic, mFemaleUrl)
                }

                mDatabind.tvEditPairFemale -> editBloodPigeonInfo("雌", femaleId)
                mDatabind.tvEditPairMale -> editBloodPigeonInfo("雄", maleId)
                mDatabind.llChooseFemalePigeon -> startActivityForResult<ActivityBreedPigeonSelection>("title" to "雌鸽选择", "isAmend" to false) {
                    mSexType = getString(R.string.hint_female)
                    val id = it?.getIntExtra("id", 0)
                    if (id != null) {
                        onRefreshDetailInfo(id)
                    }
                }

                mDatabind.llChooseFamePigeon -> startActivityForResult<ActivityBreedPigeonSelection>("title" to "雄鸽选择", "isAmend" to false) {
                    mSexType = getString(R.string.hint_male)
                    val id = it?.getIntExtra("id", 0)
                    if (id != null) {
                        onRefreshDetailInfo(id)
                    }
                }

                mDatabind.btnStartPair -> startPair()
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    private fun editBloodPigeonInfo(s: String, id: Int) {
        mSexType = s
        startActivityForResult<ActivityAddBloodPigeon>("id" to id, "type" to 3, "isAmend" to false) {
            if (it != null) {
                onRefreshDetailInfo(it.getIntExtra("id", 0))
            }
        }
    }

    private fun startPair() {
        if (mDatabind.tvMaleRingId.isEmpty()) {
            RxToast.warning(getString(R.string.please_choose_male_pigeon), 6000)
            return
        }
        if (mDatabind.tvFemaleRingId.isEmpty()) {
            RxToast.warning(getString(R.string.please_choose_female_pigeon), 6000)
            return
        }
        val mPairNum = mDatabind.etInputPairNum.text.toString().trim()
        if (mPairNum.isEmpty()) {
            RxToast.showToast(getString(R.string.please_enter_pair_number))
            return
        }
        val map = mapOf(
            "femaleId" to femaleId,
            "maleId" to maleId,
            "pairNum" to mPairNum
        )
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        showLoading(getString(R.string.loading))
        mViewModel.addBreedingPairInfo(body)
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        /** 获取种鸽详情 */
        mViewModel.detailResult.observe(this) {
            if (it != null) {
                if (mSexType == "雌") {
                    femaleId = it.id
                    mDatabind.dataFemale = it
                    mDatabind.tvFemaleRingId.text = it.year + "-" + it.area + "-" + it.ringId
                    if (it.list.isNotEmpty() && it.photoFlag > 0) {
                        it.list.forEachIndexed { index, imageListBean ->
                            if (it.photoFlag == index + 1) {
                                mFemaleUrl = imageListBean.url
                                ImageLoaderManager.loadRoundImage(this, imageListBean.url, mDatabind.ivFemalePairPic, 5)
                            }
                        }
                    }
                } else {
                    mDatabind.dataMale = it
                    maleId = it.id
                    mDatabind.tvMaleRingId.text = it.year + "-" + it.area + "-" + it.ringId
                    if (it.list.isNotEmpty() && it.photoFlag > 0) {
                        it.list.forEachIndexed { index, imageListBean ->
                            if (it.photoFlag == index + 1) {
                                mMaleUrl = imageListBean.url
                                ImageLoaderManager.loadRoundImage(this, imageListBean.url, mDatabind.ivMalePairPic, 5)
                            }
                        }
                    }
                }
                refreshLayoutStatus()
            }
        }
        /** 作育配对 */
        mViewModel.addBreedingPairInfoResult.observe(this) {
            eventViewModel.toRefreshPair.value = true
            startActivity<ActivityBreedingTracking>(
                "pairId" to it.breedingPairId,
                "maleName" to mDatabind.tvMalName.text.toString().trim(),
                "maleRingId" to mDatabind.tvMaleRingId.text.toString().trim(),
                "femaleName" to mDatabind.tvFemaleName.text.toString().trim(),
                "femaleRingId" to mDatabind.tvFemaleRingId.text.toString().trim(),
                "femaleId" to femaleId,
                "maleId" to maleId
            )
            finish()
        }
    }
}